import React from "react";
import {Menu, Button, Tree, Modal } from 'antd/lib';
import 'antd/dist/antd.less'; 
import {get} from "lodash";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import CreateTimeStructDialog from "@/components/timestruct/CreateTimeStructDialog";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import Enums from "@/services/enums";
import notification from "@/services/notification";
import "./TimeStructList.less";
import TimeStruct from "@/services/timestruct";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
const { confirm } = Modal;

class TimeStructList extends React.Component {
  state = {
    loading: true,
    calendar_enum: '',
    items: [],
    nodes: [],
    selectedKeys: [],
    selectedTitle: '',
  };

  componentWillMount() {
    this.loadEnums();
  };

  loadEnums() {    
    Enums.items('calendar_enum').then(data => {
      data && this.setState({
        items: data,
        calendar_enum: data[0].value,
      });
      this.loadData();
    });
  };

  loadData(calendar_enum=this.state.calendar_enum) {    
    TimeStruct.query(calendar_enum).then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      data && this.setState({
        loading: false,
        calendar_enum: calendar_enum,
        nodes: datas,
        selectedKeys: [],
        selectedTitle: '',
      });
    });
  }

  onSelect = (selectedKeys, e) => {
    this.setState({
      selectedKeys: selectedKeys,
      selectedTitle: e.node.props.title,
    });
};

  tabsClick = e => {
    this.loadData(e.key);
  };

  showCreateTimeStructDialog = () => {
    CreateTimeStructDialog.showModal({calendar_enum: this.state.calendar_enum, parent_id: 0})
      .onClose((result = {}) => {
        if (result.success) {
          this.loadData();
        }
      }).onDismiss(() => {
        navigateTo("timestruct", true);
      });
  };

  showCreateChildTimeStructDialog = () => {
    if (this.state.selectedKeys.length !== 1 ){
      notification.error("请选择项！");
      return;  
    }

    CreateTimeStructDialog.showModal(
      {calendar_enum: this.state.calendar_enum, parent_id: parseInt(this.state.selectedKeys[0])}
    )
      .onClose((result = {}) => {
        if (result.success) {
          this.loadData();
        }
      }).onDismiss(() => {
        navigateTo("timestruct", true);
      });
  };

  handleDelete = () => {
    if (this.state.selectedKeys.length !== 1 ){
      notification.error("请选择项！");
      return;  
    }

    confirm({
      title: `确定删除“${this.state.selectedTitle}”吗？该操作将删除该项以及其下的全部子项。`,
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        TimeStruct.delete(this.state.selectedKeys[0]).then(() => {
          this.loadData();
          notification.success("删除成功！");
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败！"));
        });
      },
    });
  };

  renderTabs() {
    return (
      <Menu onClick={this.tabsClick} selectedKeys={[this.state.calendar_enum]} mode="horizontal">
      {this.state.items.map(item => (
        <Menu.Item key = {item.value}>
          {item.label}
        </Menu.Item>
      ))}
      </Menu>
    );
 };

  render() {
    if (this.state.loading || this.state.items.length === 0) return null;

    return (
      <div className="settings-screen">
        <div className="container">
          <PageHeader title="时间结构" />
          <div className="bg-white tiled">
            {this.renderTabs()}
            <div className="bg-white tiled">
              <br/>
              <Button type="primary" onClick={this.showCreateTimeStructDialog}>
                <i className="fa fa-plus m-r-5" />
                新建
              </Button>
              <Button type="primary" onClick={this.showCreateChildTimeStructDialog} 
                disabled={this.state.selectedKeys.length===0}>
                <i className="fa fa-plus m-r-5" />
                新建下级
              </Button>
              <Button type="primary" onClick={this.handleDelete} 
                disabled={this.state.selectedKeys.length===0}>
                <i className="fa fa-remove m-r-5" />
                删除
              </Button>
              <div className="p-15">
                <Tree
                  showIcon
                  // showLine
                  switcherIcon={<DownOutlined />}
                  defaultExpandAll
                  onSelect={this.onSelect}
                  treeData={this.state.nodes}
                  />
              </div>
           </div>
          </div>
        </div>
      </div>
    );
  }
}

routes.register(
  "Timestruct.List",
  routeWithUserSession({
    path: "/timestruct",
    title: "时间结构",
    render: pageProps => <TimeStructList {...pageProps}/>,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/timestruct",
//     title: "时间结构",
//     render: pageProps => <TimeStructList {...pageProps} />,
//   }),
// ];
